import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { message } from 'ant-design-vue'
import { getToken, removeToken, isTokenExpired } from './auth'
import type { ApiResponse } from '@/types/common'

const baseURL = import.meta.env.VITE_API_BASE_URL || '/api'

const service: AxiosInstance = axios.create({
    baseURL,
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json',
    },
})

// 请求拦截器
service.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        const token = getToken()
        if (token && !isTokenExpired(token)) {
            config.headers = config.headers || {}
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    (error) => {
        console.error('Request error:', error)
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse<ApiResponse>) => {
        const { data } = response

        if (data.success) {
            return data.data
        } else {
            message.error(data.message || '请求失败')
            return Promise.reject(new Error(data.message || '请求失败'))
        }
    },
    (error) => {
        if (error.response) {
            const { status } = error.response

            switch (status) {
                case 401:
                    message.error('登录已过期，请重新登录')
                    removeToken()
                    window.location.href = '/login'
                    break
                case 403:
                    message.error('没有权限访问')
                    break
                case 404:
                    message.error('请求的资源不存在')
                    break
                case 500:
                    message.error('服务器内部错误')
                    break
                default:
                    message.error(error.response.data?.message || '请求失败')
                    break
            }
        } else if (error.request) {
            message.error('网络连接失败')
        } else {
            message.error('请求配置错误')
        }

        return Promise.reject(error)
    }
)

export default service 